package com.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.commonutils.RandomUtil;
import com.entity.excel.importData.CourseImportData;
import com.entity.pojo.Courses;
import com.handler.MyException;
import com.service.CoursesService;
import com.utils.InitData;
import org.apache.commons.collections4.ListUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class CourseExcelListener extends AnalysisEventListener<Courses> {

    // 每隔100条存储数据库
    private static final int BATCH_COUNT = 100;
    private CoursesService coursesService;
    private InitData initData;

    List<Courses> cachedDataList = new ArrayList<>(BATCH_COUNT);

    public CourseExcelListener() {
    }

    public CourseExcelListener(CoursesService coursesService, InitData initData) {
        this.coursesService = coursesService;
        this.initData = initData;
    }

    // 读取Excel数据
    @Override
    public void invoke(Courses courseImportData, AnalysisContext analysisContext) {
        // 设置课程代码
        initData.initCourse(courseImportData);
//        initCourse(courseImportData);
        courseImportData.setNextCourseStr("");
        cachedDataList.add(courseImportData);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            coursesService.saveBatch(cachedDataList);
            // 存储完成清理缓存
            cachedDataList.clear();
        }
    }

//    private void initCourse(Courses course) {
//        QueryWrapper<Courses> wrapper = new QueryWrapper<Courses>().select("max(courseId)", "courseId");
//        // 设置课程代码
//        Courses courses = coursesService.getOne(wrapper);
//        Integer maxPrimaryId;
//        if (courses == null) {
//            maxPrimaryId = 1;
//        } else {
//            maxPrimaryId = courses.getCourseId();
//        }
//        String courseCode = "A" + RandomUtil.getSixBitRandom() + maxPrimaryId;
//        course.setCourseCode(courseCode);
//    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        coursesService.saveBatch(cachedDataList);
    }
}
